import SparkMD5 from 'spark-md5'

// utils.js
export const isVideo = (file) => {
    return file.match(/\.(mp4|webm|ogg|mov)$/i);
};

// 计算MD5
export const h5CalculateMd5 = async (file) => {
    return new Promise((resolve, reject) => {
        const spark = new SparkMD5.ArrayBuffer()
        const reader = new FileReader()
        reader.readAsArrayBuffer(file)
        reader.onload = (e) => {
            spark.append(e.target.result)
            const md5 = spark.end()
            resolve(md5)
        }
        reader.onerror = (error) => {
            reject(new Error('文件读取失败'))
        }
    })
}

// H5专用上传方法
export const h5Upload = (url, file, param = {}) => {
    return new Promise((resolve, reject) => {
        const formData = new FormData()

        formData.append('file', file)

        // 添加额外参数
        Object.entries(param).forEach(([key, value]) => {
            formData.append(key, value)
        })

        const xhr = new XMLHttpRequest()
        xhr.open('POST', url)


        xhr.upload.onprogress = (e) => {
            if (e.lengthComputable) {
                const progress = Math.round((e.loaded / e.total) * 100);
                console.log('progress', progress)
            }
        }

        xhr.onload = () => {
            if (xhr.status >= 200 && xhr.status < 300) {
                const obj = JSON.parse(xhr.responseText)
                console.log('上传成功', obj)
                resolve(obj)
            } else {
                // emit('error', `上传失败: ${xhr.statusText}`)
                reject(new Error(`上传失败: ${xhr.statusText}`))
            }
        }

        xhr.onerror = () => {
            console.log('网络错误')
        }

        xhr.send(formData)
    })

}

export const handleFiles = async (files, modelValue, maxCount, emit, uploadProgress, UPLOAD_URL) => {
    const uploadedFiles = [];
    for (const file of files) {
        if (modelValue.length >= maxCount) break;
        if (!file.type.match(/^(image|video)\//)) continue;

        const previewURL = URL.createObjectURL(file);
        uploadedFiles.push(previewURL);
        uploadProgress.value[previewURL] = 0;

        const formData = new FormData();
        formData.append('file', file);

        const xhr = new XMLHttpRequest();
        xhr.open('POST', UPLOAD_URL);
        xhr.upload.onprogress = (e) => {
            if (e.lengthComputable) {
                const progress = Math.round((e.loaded / e.total) * 100);
                uploadProgress.value[previewURL] = progress;
                uploadProgress.value = { ...uploadProgress.value };
            }
        };
        xhr.onload = () => {
            if (xhr.status >= 200 && xhr.status < 300) {
                const result = JSON.parse(xhr.responseText);
                if (result.code === 0) {
                    const newModelValue = modelValue.map(item =>
                        item === previewURL ? result.data.path : item
                    );
                    emit('update:modelValue', newModelValue);
                    delete uploadProgress.value[previewURL];
                    uploadProgress.value = { ...uploadProgress.value };
                } else {
                    throw new Error(result.message || '上传失败');
                }
            } else {
                throw new Error(`HTTP错误: ${xhr.status}`);
            }
        };
        xhr.onerror = (error) => {
            console.error('XHR Error:', error);
            emit('error', '网络错误，上传失败');
        };
        xhr.send(formData);
    }
    return uploadedFiles;
};